package com.hoshiicloud.user.service.impl.organization;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.UidGenerate4C;
import com.hoshiicloud.user.entity.organization.StoreOrganizationUsers;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.organization.StoreOrganizationUsersMapper;
import com.hoshiicloud.user.service.organization.StoreOrganizationUsersService;
import com.hoshiicloud.user.service.rbac.IMemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
/**
 * <p>
 * 租户机构用户 服务实现类
 * </p>
 *
 * @author campchen
 * @since 2019-05-29
 */
@Slf4j
@Service
public class StoreOrganizationUsersServiceImpl extends ServiceImpl<StoreOrganizationUsersMapper, StoreOrganizationUsers> implements StoreOrganizationUsersService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private IMemberService memberService;

    /**
     * @return IPage
     * @description: 分页查询租户机构用户
     */
    @Override
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-分页查询租户机构用户")
    @Cacheable(cacheNames = "StoreOrganizationUsers",key ="#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public IPage<StoreOrganizationUsers> getPage(IPage page, QueryWrapper queryWrapper,String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }



    /**
    * @param id
    * @return com.hoshiicloud.organization.entity.StoreOrganizationUsers
    * @description: 根据id查询租户机构用户
    */
    @Override
    @Cacheable(cacheNames = "StoreOrganizationUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "机构（供应商）管理-租户机构用户-查询租户机构用户 ")
    public StoreOrganizationUsers getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
    * @return boolean
    * @description: 新增租户机构用户
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreOrganizationUsers", allEntries = true)
    @Logable(authName = "机构（供应商）管理-租户机构用户-新增租户机构用户")
    public String insert(StoreOrganizationUsers entity) {
        //循环结束条件
        boolean flag = true;
        String code = null;
        //设置超次
        int num = 1;
        UidGenerate4C idWorker = new UidGenerate4C(num);
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        Response response = Response.data(memberService.getById(entity.getMemberId()));
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("新增失败,会员id错误"));
        }
        while (flag) {
            num++;
            //5代表供应商 3代表店铺层面
            code = 5 + 3 + String.valueOf(idWorker.getNextId()).substring(10, 17);
            StoreOrganizationUsers storeOrganizationUsers = getByOrgcode(code);
            if (storeOrganizationUsers == null) {
                flag = false;
            }
            if (num > 1000) {
                throw new ServiceException(CommonError.error("StoreOrganizationUsers下usercode自动生成重复超过1000次，请通知管理员！"));
            }
        }
        entity.setUserCode(code);
        entity.setDeleted(0);
        entity.setLocked(0);
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return id;
    }

    /**
    * @return boolean
    * @description: 修改租户机构用户
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreOrganizationUsers", allEntries = true)
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-修改租户机构用户")
    public boolean updateById(StoreOrganizationUsers entity){
        entity.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "StoreOrganizationUsers", allEntries = true)
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-删除租户机构用户")
    public boolean deleteStoreOrganizationUsersById(Long id){
        StoreOrganizationUsers entity = this.getById(id);
        if(entity==null){
            throw new ServiceException(CommonError.error("删除店铺机构用户异常，无法找到店铺机构用户记录"));
        }
        entity.setModifiedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "StoreOrganizationUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-根据id集合查询租户机构用户")
    public List<StoreOrganizationUsers> getByIds(List<Long> ids,String key) {
        return baseMapper.selectBatchIds(ids);
    }


    public StoreOrganizationUsers getByOrgcode(String usercode) {
        Wrapper<StoreOrganizationUsers> wrapper = Wrappers.<StoreOrganizationUsers>query().lambda().eq(StoreOrganizationUsers::getUserCode, usercode);
        return baseMapper.selectOne(wrapper);
    }
}
